package com.jjb.www.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import com.hjq.base.BaseDialog;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.view.ShapeImageView;
import com.hjq.shape.view.ShapeTextView;
import com.hjq.widget.layout.NestedViewPager;
import com.jjb.www.R;
import com.jjb.www.app.AppActivity;
import com.jjb.www.app.AppFragment;
import com.jjb.www.bean.TopicBean;
import com.jjb.www.http.api.AetNumberFillInfoApi;
import com.jjb.www.http.api.AetNumberFillInfoV2Api;
import com.jjb.www.http.api.CreatePaperApi;
import com.jjb.www.http.api.ExamMessageApi;
import com.jjb.www.http.api.ExamMessageV2Api;
import com.jjb.www.http.api.GetPaperTimeInfoV2Api;
import com.jjb.www.http.api.SignApi;
import com.jjb.www.http.api.SubmitPaperApi;
import com.jjb.www.http.api.SubmitPaperV2Api;
import com.jjb.www.http.glide.GlideApp;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.dialog.AnswerSheetDialog;
import com.jjb.www.ui.dialog.AnswerSheetV2Dialog;
import com.jjb.www.ui.fragment.ComprehensiveFragment;
import com.jjb.www.ui.fragment.MultipleChoiceFragment;
import com.jjb.www.ui.fragment.SingleChoiceFragment;
import com.jjb.www.ui.fragment.TrueOrFalseFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class SequentialPracticeV2Activity extends AppActivity implements ViewPager.OnPageChangeListener{
    /**
     * 用于倒计时
     */
    private CountDownTimer mCountDownTimer;
    private ShapeTextView mTvTime;
    private ShapeTextView mTvSubmit;
    private ShapeImageView mImgBj;
    private NestedViewPager mViewPager;
    private ShapeLinearLayout mLlNumber;
    private ShapeLinearLayout mLlCollection;
    private ShapeLinearLayout mLlError;
    private ShapeLinearLayout mLlTvSizeNumber;
    private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;

    private long mHour, minute, mSeconds;
    /**
     * 1.快考 2.模考
     */
    private int quickOrMock;
    /**
     * 岗位id
     */
    private Integer sentry_id;
    /**
     * 试卷id
     */
    private String paperid;
    /**
     * 证书id
     */
    private String certificate_id;
    /**
     * 第几题没有做
     */
    private Integer order_number = 0;

    private String student_id;
    //组装得传给fragment数据
    private List<TopicBean> fragmentData;
    //答题卡集合
    private List<ExamMessageV2Api.Bean.FillListDTO> list;

    //当前题的详情
    private AetNumberFillInfoV2Api.Bean topicDetitles;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sequential_practice_v2;
    }

    @Override
    protected void initView() {
        mTvSubmit = findViewById(R.id.tv_submit);
        mViewPager = findViewById(R.id.viewPager);
        mLlNumber = findViewById(R.id.ll_number);
        mImgBj = findViewById(R.id.img_bj);
        mTvTime = findViewById(R.id.tv_time);
        mLlCollection = findViewById(R.id.ll_collection);
        mLlError = findViewById(R.id.ll_error);
        mLlTvSizeNumber = findViewById(R.id.ll_tv_size_number);
        mViewPager.addOnPageChangeListener(this);
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        setOnClickListener(mLlNumber,mTvSubmit, mLlCollection, mLlError, mLlTvSizeNumber);
    }

    @Override
    protected void initData() {
        quickOrMock = getInt("quick");
        sentry_id = getInt("sentry_id");
        student_id = getString("student_id");
        certificate_id = getString("certificate_id");
        getCePingPaperTimeInfo();
    }

    @Override
    public void onClick(View view) {
        if (view == mLlNumber) {
            //获取答题卡
            getKaAnswerSheet();
        } else if (view == mTvSubmit) {
            //交卷
            getKaAnswerSheet();
        } else if (view == mLlCollection) {
            //标记
            signData();
        }else if (view==mLlError){
            //错题上报
            Intent intent = new Intent();
            intent.putExtra("paperId", paperid);
            intent.putExtra("type",topicDetitles.getType()+"");
            intent.putExtra("question_id",topicDetitles.getQuestion_id()+"");
            intent.putExtra("order_number",topicDetitles.getOrder_number()+"");
            intent.putExtra("question_type",topicDetitles.getQuestion_type()+"");
            intent.setClass(getContext(), ErrorPostActivity.class);
            startActivity(intent);
        }

    }
    private void getCePingPaperTimeInfo() {
        EasyHttp.post(this)
                .api(new GetPaperTimeInfoV2Api()
                        .setCertificate_id(certificate_id)
                        .setStudent_id(student_id)
                        .setExam_type(quickOrMock + "")
                )
                .request(new HttpCallback<HttpData<GetPaperTimeInfoV2Api.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<GetPaperTimeInfoV2Api.Bean> data) {
                        if (data.getData().getPaper_id() != null&&!"0".equals(data.getData().getPaper_id())) {
                            //有未考试完的试卷
                            paperid = data.getData().getPaper_id();
                            //获取答题卡Answer sheet
                            getV2AnswerSheet();
                        } else {
                            //创建试卷
                            createV2Paper();
                        }
                    }
                });
    }
    private void signData() {
        EasyHttp.post(this)
                .api(new SignApi()
                        .setExam_type(quickOrMock + "")
                        .setPaper_id(paperid + "")
                        .setType(topicDetitles.getType() + "")
                        .setSign(topicDetitles.getIs_sign() == 0 ? "1" : "0")
                        .setQuestion_id(topicDetitles.getQuestion_id() + "")
                        .setOrder_number(topicDetitles.getOrder_number() + "")
                        .setQuestion_type(topicDetitles.getQuestion_type() + "")
                )
                .request(new HttpCallback<HttpData<SignApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<SignApi.Bean> data) {
                        if (topicDetitles.getIs_sign() == 1) {
                            GlideApp.with(getActivity())
                                    .load(R.mipmap.icon_bj_no)
                                    .into(mImgBj);
                        } else {
                            GlideApp.with(getActivity())
                                    .load(R.mipmap.icon_bj_yes)
                                    .into(mImgBj);
                        }
                    }
                });
    }
    private void getKaAnswerSheet() {
        list = new ArrayList<>();
        list.clear();
        EasyHttp.get(this)
                .api(new ExamMessageV2Api()
                        .setPagerId(paperid + "")
                        .setPaper_id(paperid + "")
                        .setExam_type(quickOrMock + "")
                )
                .request(new HttpCallback<HttpData<ExamMessageV2Api.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<ExamMessageV2Api.Bean> data) {
                        list = data.getData().getFill_list();

                        new AnswerSheetV2Dialog.Builder(getContext())
                                .setList(list)
                                .setListener(new AnswerSheetV2Dialog.OnListener() {
                                    @Override
                                    public void onCompleted(BaseDialog dialog, ExamMessageV2Api.Bean.FillListDTO.NumberListDTO content) {
                                        mViewPager.setCurrentItem(content.getOrder_number() - 1);
                                        if (content.getIs_sign() == 1) {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_yes)
                                                    .into(mImgBj);
                                        } else {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_no)
                                                    .into(mImgBj);
                                        }
                                    }

                                    @Override
                                    public void onCommin() {
                                        submitData();
                                    }
                                }).show();
                    }
                });
    }

    private void createV2Paper() {
        EasyHttp.post(this)
                .api(new CreatePaperApi()
                        .setExam_type(quickOrMock + "")
                        .setStudent_id(student_id+"")
                        .setSentry_id(sentry_id + "")
                )
                .request(new HttpCallback<HttpData<CreatePaperApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<CreatePaperApi.Bean> data) {
                        paperid = data.getData().getPaper_id();
                        //获取答题卡
                        getV2AnswerSheet();
                    }
                });
    }

    private void getV2AnswerSheet() {
        order_number = 0;
        fragmentData = new ArrayList<>();
        EasyHttp.get(this)
                .api(new ExamMessageV2Api()
                        .setPagerId(paperid + "")
                        .setPaper_id(paperid + "")
                        .setExam_type(quickOrMock + "")
                )
                .request(new HttpCallback<HttpData<ExamMessageV2Api.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<ExamMessageV2Api.Bean> data) {
                        showCountDownTimer(data.getData().getPaper_info().getSur_time());
                        for (ExamMessageV2Api.Bean.FillListDTO fillListDTO : data.getData().getFill_list()) {
                            Integer number = 0;
                            for (ExamMessageV2Api.Bean.FillListDTO.NumberListDTO numberListDTO : fillListDTO.getNumber_list()) {
                                TopicBean topicBean = new TopicBean();
                                topicBean.setPaperid(paperid);
                                number = number + 1;
                                topicBean.setNumber(number);
                                topicBean.setType(fillListDTO.getType());
                                topicBean.setType_test(fillListDTO.getType_test());
                                topicBean.setIs_answer(numberListDTO.getIs_answer());
                                topicBean.setIs_sign(numberListDTO.getIs_sign());
                                topicBean.setNumber_score(fillListDTO.getType_number_score());
                                topicBean.setOrder_number(numberListDTO.getOrder_number());
                                fragmentData.add(topicBean);

                                if (numberListDTO.getIs_answer() == 0 && order_number == 0) {
                                    order_number = numberListDTO.getOrder_number();
                                }
                            }
                        }

                        for (TopicBean bean : fragmentData) {
                            if (bean.getType() == 1) {
                                mPagerAdapter.addFragment(SingleChoiceFragment.newInstance("ceping",bean.getOrder_number(), Integer.parseInt(paperid), bean.getNumber_score(), bean.getNumber(), quickOrMock, new SingleChoiceFragment.OnSelectListener() {
                                    @Override
                                    public void questionDetails(AetNumberFillInfoApi.Bean details) {
                                    }

                                    @Override
                                    public void questionDetailsV2(AetNumberFillInfoV2Api.Bean details) {
                                        topicDetitles = details;
                                        if (topicDetitles.getIs_sign() == 1) {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_yes)
                                                    .into(mImgBj);
                                        } else {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_no)
                                                    .into(mImgBj);
                                        }
                                    }

                                    @Override
                                    public void nextAnswerListener(Integer index) {
                                        mViewPager.setCurrentItem(index);
                                    }
                                }), "单选题");
                            } else if (bean.getType() == 2) {
                                mPagerAdapter.addFragment(TrueOrFalseFragment.newInstance("ceping",bean.getOrder_number(), Integer.parseInt(paperid), bean.getNumber_score(), bean.getNumber(), quickOrMock, new TrueOrFalseFragment.OnSelectListener() {
                                    @Override
                                    public void questionDetails(AetNumberFillInfoApi.Bean details) {
                                    }

                                    @Override
                                    public void questionDetailsV2(AetNumberFillInfoV2Api.Bean bean) {
                                        topicDetitles = bean;
                                        if (topicDetitles.getIs_sign() == 1) {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_yes)
                                                    .into(mImgBj);
                                        } else {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_no)
                                                    .into(mImgBj);
                                        }
                                    }

                                    @Override
                                    public void nextAnswerListener(Integer index) {
                                        mViewPager.setCurrentItem(index);
                                    }
                                }), "判断题");
                            } else if (bean.getType() == 3) {
                                mPagerAdapter.addFragment(MultipleChoiceFragment.newInstance("ceping", bean.getOrder_number(), Integer.parseInt(paperid), bean.getNumber_score(), bean.getNumber(), quickOrMock, new MultipleChoiceFragment.OnSelectListener() {
                                    @Override
                                    public void questionDetails(AetNumberFillInfoApi.Bean bean) {

                                    }

                                    @Override
                                    public void questionDetailsV2(AetNumberFillInfoV2Api.Bean details) {
                                        topicDetitles = details;
                                        if (topicDetitles.getIs_sign() == 1) {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_yes)
                                                    .into(mImgBj);
                                        } else {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_no)
                                                    .into(mImgBj);
                                        }
                                    }
                                }), "多选题");
                            } else if (bean.getType() == 4) {
                                mPagerAdapter.addFragment(ComprehensiveFragment.newInstance("ceping", bean.getOrder_number(), Integer.parseInt(paperid), bean.getNumber_score(), bean.getNumber(), quickOrMock, new ComprehensiveFragment.OnSelectListener() {
                                    @Override
                                    public void questionDetails(AetNumberFillInfoApi.Bean bean) {

                                    }

                                    @Override
                                    public void questionDetailsV2(AetNumberFillInfoV2Api.Bean details) {
                                        topicDetitles = details;
                                        if (topicDetitles.getIs_sign() == 1) {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_yes)
                                                    .into(mImgBj);
                                        } else {
                                            GlideApp.with(getActivity())
                                                    .load(R.mipmap.icon_bj_no)
                                                    .into(mImgBj);
                                        }
                                    }
                                }), "综合题");
                            }

                        }
                        mViewPager.setAdapter(mPagerAdapter);
                    }
                });
    }
    /**
     * 显示倒计时
     */
    private void showCountDownTimer(long time) {
//        mTime = time*1000;
        mCountDownTimer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (!SequentialPracticeV2Activity.this.isFinishing()) {
//                    mLeftTime = millisUntilFinished;
                    long day = millisUntilFinished / (1000 * 24 * 60 * 60);
                    mHour = (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60);
                    minute = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - mHour * (1000 * 60 * 60)) / (1000 * 60);
                    mSeconds = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - mHour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;
                    if (mHour <= 0) {
                        mTvTime.setText(String.format(Locale.CHINA, "%d:%d", minute, mSeconds));
                    } else {
                        mTvTime.setText(String.format(Locale.CHINA, "%d:%d:%d", mHour, minute, mSeconds));
                    }
                }
            }

            /**
             *倒计时结束后调用的
             */
            @Override
            public void onFinish() {
                submitData();
            }

        };
        mCountDownTimer.start();
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void submitData() {
        EasyHttp.post(this)
                .api(new SubmitPaperV2Api()
                        .setExam_type(quickOrMock + "")
                        .setPaper_id(paperid + "")
                        .setStudent_id(student_id + "")
                )
                .request(new HttpCallback<HttpData<SubmitPaperV2Api.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<SubmitPaperV2Api.Bean> data) {
                        Intent intent = new Intent();
                        intent.putExtra("exam_type_name",data.getData().getExam_type_name());
                        intent.putExtra("sentry_name",data.getData().getSentry_name());
                        intent.putExtra("exam_time",data.getData().getExam_time());
                        intent.putExtra("score",data.getData().getScore()+"");
                        intent.putExtra("paper_id",data.getData().getPaper_id()+"");
                        intent.setClass(getContext(),ExamResultsActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
    }
    public void release(){
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void onBackPressed() {
        getKaAnswerSheet();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }
}